#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <malloc.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <linux/if.h>

#define IFNAMSIZE 16

int get_gw_ip(char * eth, char * ipaddr)
{
  int sock_fd;
  struct sockaddr_in addr;
  struct ifreq ifr;

  /* get socket file descriptor */
  if ((sock_fd = socket(PF_INET, SOCK_DGRAM, 0)) == -1) {
    perror("socket");
    return -1;
  }

  /* get ip address */
  strncpy(ifr.ifr_name, eth, IFNAMSIZE);
  ifr.ifr_name[IFNAMSIZE - 1] = '\0';

  if (ioctl(sock_fd, SIOCGIFADDR, &ifr) < 0) {
    printf("no such device %s\n", eth);
    return -1;
  }

  memcpy(&addr, &ifr.ifr_addr, sizeof(addr));
  strcpy(ipaddr, inet_ntoa(addr.sin_addr));
  close(sock_fd);

  return 0;
}

void main()
{
  char eth[32] = {'e','t','h','0'};
  char ipaddr[32] = {0};

  get_gw_ip("usb0", ipaddr);
  if (strlen(ipaddr) == 0)
    printf("ip:null\n");
  else
    printf("ip:%s\n", ipaddr);

  if (ipaddr[0] == '\0')
    printf("ip:null\n");
  else
    printf("ip:%s\n", ipaddr);

  memset(ipaddr, 0, 32);
  get_gw_ip("lo", ipaddr);
  printf("ip:%s\n", ipaddr);
}
